﻿using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;


public class Obstacle : MonoBehaviour {

	[Serializable]
	public class WayPoint {
		public Transform transform;
		public float duration = 1f;
	}

	public WayPoint[] wayPoints;
	public float rotateSpeed = 0f;

	protected int _prevWayPointIndex = 0;
	protected int _currentWayPointIndex = 1;
	protected float _currentWayPointTimer = 0f;

	void Start () {
		if (wayPoints != null && wayPoints.Length > 1) {
			transform.position = wayPoints[0].transform.position;
		}
	}

	void FixedUpdate () {
		if (wayPoints != null && wayPoints.Length > 1) {
			WayPoint currentWayPoint = wayPoints[_currentWayPointIndex];

			_currentWayPointTimer += Time.fixedDeltaTime;

			while (_currentWayPointTimer > currentWayPoint.duration) {
				_currentWayPointTimer -= currentWayPoint.duration;

				_prevWayPointIndex = _currentWayPointIndex;
				_currentWayPointIndex++;
				if (_currentWayPointIndex >= wayPoints.Length) {
					_currentWayPointIndex = 0;
				}
				Log(gameObject.name + " GOTO WP[" + _currentWayPointIndex + "]");

				currentWayPoint = wayPoints[_currentWayPointIndex];
			}
				
			WayPoint prevWayPoint = wayPoints[_prevWayPointIndex];
			transform.position = Vector3.Lerp(prevWayPoint.transform.position, 
				currentWayPoint.transform.position, 
				Mathf.Clamp01(_currentWayPointTimer / currentWayPoint.duration));
		}

		if (rotateSpeed != 0f) {
			transform.Rotate(Vector3.forward, rotateSpeed * Time.fixedDeltaTime);
		}
	}

	protected static void Log(string message) {
		Debug.Log("<color=yellow>" + message + "</color>");
	}

}
